<template>
  <div class="goods-detail-page">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="spinner"></div>
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <i class="fa fa-exclamation-circle"></i>
      <p>{{ errorMessage }}</p>
      <button @click="fetchGoodsDetail" class="retry-btn">重试</button>
    </div>

    <!-- 商品详情内容 -->
    <div v-else-if="goodsDetail" class="goods-content">
      <!-- 商品主信息区域 -->
      <div class="goods-main">
        <!-- 商品图片区域 -->
        <div class="goods-images">
          <div class="main-image">
            <img :src="currentImage" :alt="goodsDetail.goods_name" />
            <div v-if="goodsDetail.is_flash_sale" class="flash-sale-badge">秒杀商品</div>
          </div>
          <div class="thumbnail-list">
            <div
              v-for="(img, index) in goodsDetail.goods_carousel"
              :key="index"
              class="thumbnail-item"
              :class="{ active: currentImgIndex === index }"
              @click="currentImgIndex = index"
            >
              <img :src="img" :alt="`缩略图 ${index + 1}`" />
            </div>
          </div>
        </div>

        <!-- 商品基本信息 -->
        <div class="goods-info">
          <h1 class="goods-title">{{ goodsDetail.goods_name }}</h1>
          <p class="goods-desc">{{ goodsDetail.goods_desc }}</p>

          <!-- 秒杀信息提示 -->
          <div v-if="goodsDetail.is_flash_sale" class="flash-sale-alert">
            <i class="fa fa-bolt"></i>
            <span>限时秒杀进行中，优惠不容错过！</span>
          </div>

          <div class="price-section">
            <div class="price-container">
              <span v-if="goodsDetail.is_flash_sale" class="flash-price"
                >¥{{ goodsDetail.flash_sale_price }}</span
              >
              <span v-else class="current-price">¥{{ goodsDetail.goods_price }}</span>
              <span class="market-price">¥{{ goodsDetail.market_price }}</span>
              <span class="discount">省¥{{ computeDiscountAmount() }}</span>
            </div>
            <div class="price-tag">
              <span v-if="goodsDetail.is_flash_sale" class="flash-tag">秒杀价</span>
              <span v-else class="tag">优惠价</span>
            </div>
          </div>

          <!-- 秒杀倒计时和库存信息 -->
          <div v-if="goodsDetail.is_flash_sale" class="flash-sale-info">
            <div class="flash-sale-timer">
              <i class="fa fa-clock-o"></i>
              <span>剩余时间: {{ formatTimeRemaining() }}</span>
            </div>
            <div class="flash-sale-stock">
              <i class="fa fa-cubes"></i>
              <span>秒杀库存: {{ goodsDetail.flash_sale_stock }}件</span>
            </div>
            <div v-if="!isFlashSaleActive" class="flash-sale-inactive">
              <i class="fa fa-exclamation-triangle"></i>
              <span>{{ flashSaleInactiveMessage }}</span>
            </div>
          </div>

          <div class="sales-info">
            <div class="info-item">
              <span class="label">销量</span>
              <span class="value">{{ goodsDetail.goods_sales }}件</span>
            </div>
            <div v-if="!goodsDetail.is_flash_sale" class="info-item">
              <span class="label">库存</span>
              <span class="value">{{ goodsDetail.goods_stock }}件</span>
            </div>
            <div class="info-item">
              <span class="label">分类</span>
              <span class="value">{{ goodsDetail.category?.category_name || '暂无分类' }}</span>
            </div>
          </div>

          <!-- 数量选择 -->
          <div class="quantity-selector">
            <span class="label">数量</span>
            <div class="quantity-control">
              <button
                class="quantity-btn"
                @click="decreaseQuantity"
                :disabled="quantity <= 1 || !canPurchase"
              >
                -
              </button>
              <input
                type="number"
                v-model.number="quantity"
                min="1"
                :max="purchaseLimit"
                class="quantity-input"
                @change="validateQuantity"
                :disabled="!canPurchase"
              />
              <button
                class="quantity-btn"
                @click="increaseQuantity"
                :disabled="quantity >= purchaseLimit || !canPurchase"
              >
                +
              </button>
            </div>
            <span class="stock-info">库存: {{ purchaseLimit }}件</span>
            <span v-if="!canPurchase" class="purchase-disabled-text">{{
              purchaseDisabledReason
            }}</span>
          </div>

          <!-- 规格显示 -->
          <div class="specs-selector" v-if="goodsDetail.specs && goodsDetail.specs.length">
            <div v-for="spec in goodsDetail.specs" :key="spec.spec_id" class="spec-item">
              <span class="spec-name">{{ spec.spec_name }}:</span>
              <span class="spec-value">{{ spec.spec_value }}</span>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <button class="add-cart-btn" @click="handleAddToCart" :disabled="!canPurchase">
              <i class="fa fa-shopping-cart"></i>
              {{ canPurchase ? '加入购物车' : purchaseButtonText }}
            </button>
            <button class="buy-now-btn" @click="handleBuyNow" :disabled="!canPurchase">
              {{ canPurchase ? '立即购买' : purchaseButtonText }}
            </button>
            <button class="favorite-btn" @click="handleToggleFavorite">
              <i class="fa" :class="isFavorite ? 'fa-heart' : 'fa-heart-o'"></i>
              {{ isFavorite ? '已收藏' : '收藏' }}
            </button>
          </div>

          <!-- 服务承诺 -->
          <div class="service-promise">
            <div class="service-item">
              <i class="fa fa-shield"></i>
              <span>正品保证</span>
            </div>
            <div class="service-item">
              <i class="fa fa-truck"></i>
              <span>快速配送</span>
            </div>
            <div class="service-item">
              <i class="fa fa-refresh"></i>
              <span>7天无理由退货</span>
            </div>
            <div class="service-item">
              <i class="fa fa-certificate"></i>
              <span>1年质保</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品详情区域 -->
      <div class="goods-detail-section">
        <div class="section-tabs">
          <div
            class="tab-item"
            :class="{ active: activeTab === 'detail' }"
            @click="activeTab = 'detail'"
          >
            <i class="fa fa-file-text-o"></i>
            商品详情
          </div>
          <div
            class="tab-item"
            :class="{ active: activeTab === 'params' }"
            @click="activeTab = 'params'"
          >
            <i class="fa fa-list-alt"></i>
            商品参数
          </div>
          <div
            class="tab-item"
            :class="{ active: activeTab === 'comments' }"
            @click="activeTab = 'comments'"
          >
            <i class="fa fa-comments-o"></i>
            用户评价
          </div>
        </div>

        <div class="tab-content">
          <!-- 商品详情 -->
          <div v-if="activeTab === 'detail'" class="detail-content">
            <div class="detail-header">
              <h3>商品详情</h3>
              <p>全方位展示商品细节，让您购物更放心</p>
            </div>
            <div
              v-if="goodsDetail.goods_detail_content"
              class="detail-html"
              v-html="goodsDetail.goods_detail_content"
            ></div>
            <div v-else class="no-detail">
              <img src="https://via.placeholder.com/800x400?text=商品详情图" alt="商品详情" />
              <p>暂无商品详情信息</p>
            </div>
          </div>

          <!-- 商品参数 -->
          <div v-if="activeTab === 'params'" class="params-content">
            <div class="params-header">
              <h3>商品参数</h3>
              <p>详细了解商品规格参数</p>
            </div>
            <div v-if="goodsDetail.params && goodsDetail.params.length" class="params-list">
              <div v-for="(param, index) in goodsDetail.params" :key="index" class="param-item">
                <span class="param-name">{{ param.param_name }}</span>
                <span class="param-value">{{ param.param_value }}</span>
              </div>
            </div>
            <div v-else class="no-params">
              <i class="fa fa-info-circle"></i>
              <p>暂无商品参数信息</p>
            </div>
          </div>

          <!-- 用户评价 -->
          <div v-if="activeTab === 'comments'" class="comments-content">
            <div class="comments-header">
              <h3>用户评价</h3>
              <div class="rating-overview">
                <div class="rating-score">
                  <span class="score">{{ calculateAverageRating() }}</span>
                  <span class="total">/5分</span>
                </div>
                <div class="rating-stars">
                  <i
                    v-for="star in 5"
                    :key="star"
                    class="fa"
                    :class="star <= Math.round(calculateAverageRating()) ? 'fa-star' : 'fa-star-o'"
                  ></i>
                </div>
                <span class="rating-count">{{ comments.length }}条评价</span>
              </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="commentsLoading" class="loading-container">
              <div class="spinner"></div>
              <p>加载评论中...</p>
            </div>

            <!-- 错误状态 -->
            <div v-else-if="commentsError" class="error-container">
              <i class="fa fa-exclamation-circle"></i>
              <p>加载评论失败</p>
              <button @click="loadComments" class="retry-btn">重试</button>
            </div>

            <!-- 空状态 -->
            <div v-else-if="comments.length === 0" class="empty-container">
              <i class="fa fa-comment"></i>
              <p>暂无评价</p>
            </div>

            <!-- 评论列表 -->
            <div v-else class="comments-list">
              <div v-for="comment in comments" :key="comment.comment_id" class="comment-item">
                <div class="user-info">
                  <div class="avatar-container">
                    <img
                      v-if="comment.user_info?.avatar_url"
                      :src="comment.user_info.avatar_url"
                      :alt="comment.user_info.username || '用户头像'"
                      class="avatar"
                      @error="handleAvatarError"
                    />
                    <div v-else class="avatar placeholder">
                      <i class="fa fa-user"></i>
                    </div>
                  </div>
                  <span class="username">{{ comment.user_info?.username || '匿名用户' }}</span>
                </div>
                <div class="comment-content">
                  <div class="comment-rating">
                    <i
                      v-for="star in 5"
                      :key="star"
                      class="fa"
                      :class="star <= comment.rating ? 'fa-star' : 'fa-star-o'"
                    ></i>
                  </div>
                  <p>{{ comment.content }}</p>
                  <div v-if="comment.images && comment.images.length > 0" class="comment-images">
                    <div
                      v-for="image in comment.images"
                      :key="image.image_id"
                      class="image-item"
                      @click="previewImage(image.image_url_full || image.image_url)"
                    >
                      <img
                        :src="image.image_url_full || image.image_url"
                        alt="评论图片"
                        @error="handleImageError"
                      />
                    </div>
                  </div>
                  <span class="comment-date">{{ formatCommentTime(comment.comment_time) }}</span>

                  <!-- 商家回复 -->
                  <div v-if="comment.reply_content" class="comment-reply">
                    <div class="reply-header">
                      <span class="reply-label">商家回复：</span>
                      <span class="reply-time" v-if="comment.reply_time">{{
                        formatCommentTime(comment.reply_time)
                      }}</span>
                    </div>
                    <p class="reply-content">{{ comment.reply_content }}</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 确认弹窗 -->
    <div v-if="showConfirmModal" class="modal-overlay" @click="closeModal">
      <div class="confirm-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ modalTitle }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-content">
          <div class="confirm-goods-info">
            <img :src="currentImage" :alt="goodsDetail.goods_name" class="confirm-goods-img" />
            <div class="confirm-goods-details">
              <h4>{{ goodsDetail.goods_name }}</h4>
              <p class="confirm-price">¥{{ goodsDetail.goods_price }}</p>
              <div v-if="selectedSpecsText" class="confirm-specs">
                <span>已选：{{ selectedSpecsText }}</span>
              </div>
              <div class="confirm-quantity">
                <span>数量：{{ quantity }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-actions">
          <button class="cancel-btn" @click="closeModal">取消</button>
          <button class="confirm-btn" @click="confirmAction">
            {{ confirmButtonText }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useAuthStore } from '@/stores/useAuthStore'
import { useCartStore } from '@/stores/useCartStore'
import { useRoute, useRouter } from 'vue-router'
import { goodsApi } from '@/api/goods'
import { cartApi } from '@/api/cart'
import { ordersApi } from '@/api/orders'
import { favoritesApi, isGoodsFavorited, toggleFavorite } from '@/api/favorites'
import { commentsApi, formatCommentTime } from '@/api/comments'
import { ElMessage, ElMessageBox } from 'element-plus'

// 路由参数获取
const route = useRoute()
const router = useRouter()
const goodsId = Number(route.params.id)
const authStore = useAuthStore()
const cartStore = useCartStore()

// 状态管理
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('')
const goodsDetail = ref(null)
const currentImgIndex = ref(0)
const activeTab = ref('detail')
const isFavorite = ref(false)
const comments = ref([])
const commentsLoading = ref(false)
const commentsError = ref(false)

// 购物车选项
const quantity = ref(1)
const selectedSpecs = ref({})
const showConfirmModal = ref(false)
const modalType = ref('') // 'cart' 或 'buy'

// 收藏功能
const checkFavoriteStatus = async () => {
  console.log('开始检查收藏状态，用户登录状态:', authStore.isAuthenticated())
  console.log('商品ID:', goodsId)

  // 未登录用户默认未收藏
  if (!authStore.isAuthenticated()) {
    console.log('用户未登录，设置收藏状态为 false')
    isFavorite.value = false
    return
  }

  try {
    console.log('正在调用 isGoodsFavorited API...')
    const favoriteStatus = await isGoodsFavorited(goodsId)
    console.log('收藏状态检查结果:', favoriteStatus)
    isFavorite.value = favoriteStatus
  } catch (error) {
    console.error('检查收藏状态失败:', error)
    isFavorite.value = false
  }
}

const handleToggleFavoriteAction = async () => {
  if (!authStore.isAuthenticated()) {
    router.push('/login')
    return
  }

  try {
    isFavorite.value = await toggleFavorite(goodsId)
    ElMessage.success(isFavorite.value ? '已添加到收藏' : '已取消收藏')
  } catch (error) {
    console.error('切换收藏状态失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 秒杀相关计算属性
const isFlashSaleActive = computed(() => {
  if (!goodsDetail.value?.is_flash_sale) return false

  const now = new Date()
  const startTime = new Date(goodsDetail.value.flash_sale_start_time)
  const endTime = new Date(goodsDetail.value.flash_sale_end_time)

  return now >= startTime && now <= endTime && goodsDetail.value.flash_sale_stock > 0
})

const flashSaleInactiveMessage = computed(() => {
  if (!goodsDetail.value?.is_flash_sale) return ''

  const now = new Date()
  const startTime = new Date(goodsDetail.value.flash_sale_start_time)
  const endTime = new Date(goodsDetail.value.flash_sale_end_time)

  if (now < startTime) {
    const timeDiff = startTime.getTime() - now.getTime()
    const hours = Math.floor(timeDiff / (1000 * 60 * 60))
    const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60))
    return `秒杀尚未开始，将在 ${hours}小时${minutes}分钟后开始`
  } else if (now > endTime) {
    return '秒杀已结束'
  } else if (goodsDetail.value.flash_sale_stock <= 0) {
    return '秒杀商品已售罄'
  }
  return ''
})

const canPurchase = computed(() => {
  if (!goodsDetail.value) return false

  if (goodsDetail.value.is_flash_sale) {
    return isFlashSaleActive.value && goodsDetail.value.flash_sale_stock > 0
  }

  return goodsDetail.value.goods_stock > 0
})

const purchaseLimit = computed(() => {
  if (!goodsDetail.value) return 0

  if (goodsDetail.value.is_flash_sale) {
    return Math.min(goodsDetail.value.flash_sale_stock, goodsDetail.value.goods_stock)
  }

  return goodsDetail.value.goods_stock
})

const purchaseDisabledReason = computed(() => {
  if (canPurchase.value) return ''

  if (goodsDetail.value?.is_flash_sale) {
    return flashSaleInactiveMessage.value
  }

  return '商品已售罄'
})

const purchaseButtonText = computed(() => {
  if (canPurchase.value) return ''

  if (goodsDetail.value?.is_flash_sale) {
    if (new Date() < new Date(goodsDetail.value.flash_sale_start_time)) {
      return '秒杀未开始'
    } else if (new Date() > new Date(goodsDetail.value.flash_sale_end_time)) {
      return '秒杀已结束'
    } else if (goodsDetail.value.flash_sale_stock <= 0) {
      return '已抢光'
    }
  }

  return '已售罄'
})

// 原有计算属性
const currentImage = computed(() => {
  if (!goodsDetail.value || !goodsDetail.value.goods_carousel) return ''
  return goodsDetail.value.goods_carousel[currentImgIndex.value]
})

const selectedSpecsText = computed(() => {
  if (!selectedSpecs.value) return ''
  return Object.values(selectedSpecs.value)
    .map((option) => option.option_name)
    .join('，')
})

const modalTitle = computed(() => {
  return modalType.value === 'cart' ? '确认加入购物车' : '确认立即购买'
})

const confirmButtonText = computed(() => {
  return modalType.value === 'cart' ? '确认加入' : '立即购买'
})

// 方法
const computeDiscountAmount = () => {
  if (!goodsDetail.value) return '0.00'

  if (goodsDetail.value.is_flash_sale && goodsDetail.value.flash_sale_price) {
    return (
      parseFloat(goodsDetail.value.market_price) - parseFloat(goodsDetail.value.flash_sale_price)
    ).toFixed(2)
  }

  return (
    parseFloat(goodsDetail.value.market_price) - parseFloat(goodsDetail.value.goods_price)
  ).toFixed(2)
}

const formatTimeRemaining = () => {
  if (!goodsDetail.value?.is_flash_sale || !isFlashSaleActive.value) return ''

  const now = new Date()
  const endTime = new Date(goodsDetail.value.flash_sale_end_time)
  const timeDiff = endTime.getTime() - now.getTime()

  const hours = Math.floor(timeDiff / (1000 * 60 * 60))
  const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000)

  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

const fetchGoodsDetail = async () => {
  try {
    loading.value = true
    error.value = false
    const data = await goodsApi.getGoodsDetail(goodsId)
    goodsDetail.value = data

    // 如果有规格选项，处理规格数据
    if (data.specs && data.specs.length > 0) {
      data.specs.forEach((spec) => {
        // 根据API响应结构调整，specs可能没有options字段
        if (spec.spec_name) {
          selectedSpecs.value[spec.spec_name] = {
            option_name: spec.spec_value || '默认',
            option_id: spec.spec_id || 0,
          }
        }
      })
    }

    // 检查收藏状态
    console.log('获取商品详情完成，开始检查收藏状态')
    await checkFavoriteStatus()
    console.log('收藏状态检查完成，isFavorite:', isFavorite.value)

    // 如果切换到评论tab，加载评论
    if (activeTab.value === 'comments') {
      await loadComments()
    }
  } catch (err) {
    error.value = true
    errorMessage.value = err instanceof Error ? err.message : '获取商品详情失败，请稍后重试'
    console.error('获取商品详情失败:', err)
  } finally {
    loading.value = false
  }
}

const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
  }
}

const increaseQuantity = () => {
  if (quantity.value < goodsDetail.value.goods_stock) {
    quantity.value++
  }
}

const validateQuantity = () => {
  if (quantity.value < 1) {
    quantity.value = 1
  } else if (quantity.value > purchaseLimit.value) {
    quantity.value = purchaseLimit.value
  }
}

const selectSpec = (specName, option) => {
  if (option.stock <= 0) return
  selectedSpecs.value[specName] = option
}

const handleAddToCart = () => {
  if (!validateSelection()) return
  modalType.value = 'cart'
  showConfirmModal.value = true
}

const handleBuyNow = () => {
  if (!validateSelection()) return
  modalType.value = 'buy'
  showConfirmModal.value = true
}

const validateSelection = () => {
  if (!goodsDetail.value) return false

  // 检查是否选择了所有规格
  if (goodsDetail.value.specs && goodsDetail.value.specs.length > 0) {
    const unselectedSpecs = goodsDetail.value.specs.filter(
      (spec) => !selectedSpecs.value[spec.spec_name],
    )
    if (unselectedSpecs.length > 0) {
      alert(`请选择${unselectedSpecs.map((s) => s.spec_name).join('、')}`)
      return false
    }
  }

  // 检查库存
  if (quantity.value > purchaseLimit.value) {
    alert('购买数量不能超过库存数量')
    return false
  }

  // 检查秒杀状态
  if (goodsDetail.value.is_flash_sale && !isFlashSaleActive.value) {
    alert(flashSaleInactiveMessage.value)
    return false
  }

  return true
}

const confirmAction = async () => {
  if (modalType.value === 'cart') {
    await addToCart()
  } else {
    await buyNow()
  }
  closeModal()
}

const closeModal = () => {
  showConfirmModal.value = false
  modalType.value = ''
}

// 加载评论
const loadComments = async () => {
  if (!goodsDetail.value) return

  try {
    commentsLoading.value = true
    commentsError.value = false
    const response = await commentsApi.getGoodsComments(goodsDetail.value.goods_id)
    comments.value = response
    console.log('加载评论成功:', response.length, '条评论')
  } catch (err) {
    console.error('加载评论失败:', err)
    commentsError.value = true
  } finally {
    commentsLoading.value = false
  }
}

// 监听tab切换
watch(
  () => activeTab.value,
  (newTab) => {
    if (newTab === 'comments' && goodsDetail.value && comments.value.length === 0) {
      loadComments()
    }
  },
)

const addToCart = async () => {
  try {
    await cartStore.addToCart(goodsDetail.value.goods_id, quantity.value)
    alert(`已将 ${quantity.value}件 ${goodsDetail.value.goods_name} 加入购物车`)
  } catch (error) {
    console.error('加入购物车失败:', error)
    handleApiError(error)
  }
}

const buyNow = async () => {
  try {
    // 对于立即购买，先将商品添加到购物车
    const cartResponse = await cartApi.addToCart({
      goods: goodsDetail.value.goods_id,
      goods_num: quantity.value,
    })

    alert(`商品已添加到购物车`)

    // 跳转到结账页面
    router.push('/checkout')
  } catch (error) {
    console.error('立即购买失败:', error)
    handleApiError(error)
  }
}

const handleApiError = (error) => {
  if (error.code === 400) {
    alert('商品信息错误，请刷新页面重试')
  } else if (error.code === 401) {
    alert('请先登录')
    // router.push('/login')
  } else if (error.code === 404) {
    alert('商品不存在或已下架')
  } else {
    alert('操作失败，请稍后重试')
  }
}

const handleToggleFavorite = async () => {
  if (!goodsDetail.value) return

  try {
    if (isFavorite.value) {
      await favoritesApi.removeFromFavorites(goodsDetail.value.goods_id)
      isFavorite.value = false
      ElMessage.success('已取消收藏')
    } else {
      await favoritesApi.addToFavorites({ goods_id: goodsDetail.value.goods_id })
      isFavorite.value = true
      ElMessage.success('已添加到收藏')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 计算平均评分
const calculateAverageRating = () => {
  if (comments.value.length === 0) return 0
  const total = comments.value.reduce((sum, comment) => sum + comment.rating, 0)
  return (total / comments.value.length).toFixed(1)
}

// 头像错误处理
const handleAvatarError = (event) => {
  const img = event.target
  img.style.display = 'none'
  const placeholder = img.parentElement.querySelector('.avatar.placeholder')
  if (placeholder) {
    placeholder.style.display = 'flex'
  }
}

// 图片错误处理
const handleImageError = (event) => {
  const img = event.target
  img.style.display = 'none'
}

// 图片预览
const previewImage = (imageUrl) => {
  window.open(imageUrl, '_blank')
}

onMounted(() => {
  console.log('商品详情页 mounted，商品ID:', goodsId)
  if (goodsId) {
    fetchGoodsDetail()
  } else {
    loading.value = false
    error.value = true
    errorMessage.value = '商品ID不存在'
  }
})
</script>

<style scoped>
.goods-detail-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 数量选择器样式 */
.quantity-selector {
  display: flex;
  align-items: center;
  margin: 15px 0;
  gap: 15px;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background: #f5f5f5;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-input {
  width: 50px;
  height: 30px;
  text-align: center;
  border: 1px solid #ddd;
  margin: 0 5px;
}

.stock-info {
  color: #666;
  font-size: 14px;
}

/* 规格显示样式 */
.specs-selector {
  margin: 20px 0;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 6px;
  border: 1px solid #eee;
}

.spec-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #eee;
}

.spec-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.spec-name {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  min-width: 60px;
}

.spec-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
  text-align: right;
}

/* 确认弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.confirm-modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.modal-content {
  padding: 20px;
}

.confirm-goods-info {
  display: flex;
  gap: 15px;
}

.confirm-goods-img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.confirm-goods-details {
  flex: 1;
}

.confirm-goods-details h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
  line-height: 1.4;
}

.confirm-price {
  color: #e4393c;
  font-weight: bold;
  font-size: 16px;
  margin: 5px 0;
}

.confirm-specs,
.confirm-quantity {
  font-size: 12px;
  color: #666;
  margin: 3px 0;
}

.modal-actions {
  display: flex;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.cancel-btn,
.confirm-btn {
  flex: 1;
  padding: 10px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
}

.cancel-btn:hover {
  background: #e8e8e8;
}

.confirm-btn {
  background: #e4393c;
  color: white;
}

.confirm-btn:hover {
  background: #c03537;
}

/* 其他原有样式保持不变 */
.loading-container {
  text-align: center;
  padding: 100px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 20px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #e4393c;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.error-container {
  text-align: center;
  padding: 100px 0;
  color: #e4393c;
}

.error-container i {
  font-size: 48px;
  margin-bottom: 15px;
}

.retry-btn {
  margin-top: 15px;
  padding: 10px 20px;
  background-color: #e4393c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.retry-btn:hover {
  background-color: #c03537;
}

.goods-main {
  display: flex;
  background: white;
  border-radius: 8px;
  padding: 25px;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  gap: 30px;
}

.goods-images {
  flex: 0 0 45%;
  max-width: 500px;
}

.main-image {
  width: 100%;
  height: 450px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f9f9f9;
  border: 1px solid #eee;
}

.main-image img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.thumbnail-list {
  display: flex;
  gap: 10px;
  overflow-x: auto;
  padding-bottom: 5px;
}

.thumbnail-item {
  width: 80px;
  height: 80px;
  border: 2px solid transparent;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  flex-shrink: 0;
}

.thumbnail-item.active {
  border-color: #e4393c;
}

.thumbnail-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.goods-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.goods-title {
  font-size: 22px;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 5px;
}

.goods-desc {
  color: #e4393c;
  font-size: 14px;
  background: #fff2f2;
  padding: 8px 12px;
  border-radius: 4px;
  border-left: 3px solid #e4393c;
}

.price-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: #fff8f8;
  padding: 15px;
  border-radius: 6px;
}

.price-container {
  display: flex;
  align-items: baseline;
  gap: 10px;
}

.current-price {
  font-size: 28px;
  color: #e4393c;
  font-weight: bold;
}

.market-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
}

.discount {
  font-size: 14px;
  color: #e4393c;
  background: #ffebeb;
  padding: 2px 6px;
  border-radius: 3px;
}

.price-tag .tag {
  background: #e4393c;
  color: white;
  padding: 4px 8px;
  border-radius: 3px;
  font-size: 12px;
}

.sales-info {
  display: flex;
  gap: 30px;
  padding: 15px 0;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-item .label {
  color: #999;
  font-size: 13px;
}

.info-item .value {
  color: #666;
  font-size: 15px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 10px;
}

.add-cart-btn,
.buy-now-btn,
.favorite-btn {
  flex: 1;
  padding: 12px 0;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.add-cart-btn {
  background-color: #ff6b6b;
  color: white;
}

.add-cart-btn:hover {
  background-color: #ff5252;
}

.buy-now-btn {
  background-color: #e4393c;
  color: white;
}

.buy-now-btn:hover {
  background-color: #c03537;
}

.favorite-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
}

.favorite-btn:hover {
  background-color: #eee;
}

.service-promise {
  display: flex;
  justify-content: space-between;
  padding: 15px 0;
  border-top: 1px solid #eee;
}

.service-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 13px;
  color: #666;
}

.service-item i {
  color: #e4393c;
}

.goods-detail-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.section-tabs {
  display: flex;
  border-bottom: 1px solid #eee;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.tab-item.active {
  color: #e4393c;
  border-bottom: 2px solid #e4393c;
  font-weight: 500;
}

.tab-item:hover:not(.active) {
  background-color: #f8f9fa;
}

.tab-content {
  padding: 30px;
}

.detail-header,
.params-header,
.comments-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.detail-header h3,
.params-header h3,
.comments-header h3 {
  font-size: 18px;
  color: #333;
  margin-bottom: 5px;
}

.detail-header p,
.params-header p {
  color: #999;
  font-size: 14px;
}

.detail-html {
  line-height: 1.8;
}

.detail-html img {
  max-width: 100%;
  height: auto;
  margin: 10px 0;
}

.no-detail,
.no-params {
  text-align: center;
  padding: 50px 0;
  color: #999;
}

.no-detail img {
  max-width: 100%;
  margin-bottom: 15px;
  border-radius: 6px;
}

.params-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.param-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px dashed #eee;
}

.param-name {
  color: #666;
}

.param-value {
  color: #333;
  font-weight: 500;
}

.rating-overview {
  display: flex;
  align-items: center;
  gap: 15px;
}

.rating-score {
  display: flex;
  align-items: baseline;
}

.rating-score .score {
  font-size: 28px;
  color: #e4393c;
  font-weight: bold;
}

.rating-score .total {
  color: #999;
}

.rating-stars {
  color: #ffc107;
}

.rating-count {
  color: #666;
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  display: flex;
  gap: 15px;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  width: 80px;
}

.user-info img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.comment-content {
  flex: 1;
}

.comment-rating {
  color: #ffc107;
  margin-bottom: 5px;
}

.comment-images {
  display: flex;
  gap: 10px;
  margin: 10px 0;
}

.comment-images img {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
}

.comment-date {
  color: #999;
  font-size: 13px;
}

@media (max-width: 768px) {
  .goods-main {
    flex-direction: column;
    padding: 15px;
  }

  .goods-images {
    max-width: 100%;
  }

  .main-image {
    height: 300px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .params-list {
    grid-template-columns: 1fr;
  }

  .service-promise {
    flex-wrap: wrap;
    gap: 10px;
  }

  .service-item {
    flex: 0 0 calc(50% - 5px);
  }

  .confirm-modal {
    width: 95%;
    margin: 20px;
  }

  .confirm-goods-info {
    flex-direction: column;
    text-align: center;
  }

  .modal-actions {
    flex-direction: column;
  }
}
</style>
